package com.xinshujia.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.xinshujia.dao.DeviceDao;
import com.xinshujia.entity.DeviceEntity;
import com.xinshujia.service.DeviceService;
import com.xinshujia.utils.Constants;
import org.springframework.stereotype.Service;
import org.springframework.util.ObjectUtils;
import org.springframework.util.StringUtils;

import java.util.ArrayList;
import java.util.List;

/**
 * *************************************
 * *   @author: 野狼上校               **
 * *   @since: 2024-08-06 15:19       **
 * *   @version: 1.0                  **
 * *************************************
 * <p>
 *     设备业务实现类
 */
@Service
public class DeviceServiceImpl extends ServiceImpl<DeviceDao, DeviceEntity> implements DeviceService {
    private final DeviceDao deviceDao;

    public DeviceServiceImpl(DeviceDao deviceDao) {
        this.deviceDao = deviceDao;
    }

    /**
     * 分页查询
     */
    @Override
    public Page<DeviceEntity> getDevicesByPage(Long pageNum, Long pageSize, String companyName) {
        QueryWrapper<DeviceEntity> queryWrapper = new QueryWrapper<>();
        if(StringUtils.hasLength(companyName)){
            queryWrapper.like("company", companyName);
        }
        Page<DeviceEntity> page = new Page<>(pageNum, pageSize);
        return deviceDao.selectPage(page, queryWrapper);
    }

    /**
     * 添加设备
     */
    @Override
    public boolean insertDevice(DeviceEntity deviceEntity) {
        // 设置设备在线状态 todo 根据是否有振动值来判断
        deviceEntity.setDeviceOnline(Constants.ONLINE_STATUS);
        // 设置设备报警状态
        deviceEntity.setAlarmStatus(Constants.ALARM_STATUS_OPEN);
        return deviceDao.insert(deviceEntity) > 0;
    }

    /**
     * 所有的设备列表
     */
    @Override
    public List<DeviceEntity> getAllDevices() {
        List<DeviceEntity> deviceEntities = deviceDao.selectList(new QueryWrapper<>());
        List<DeviceEntity> devices = new ArrayList<>();
        if(!ObjectUtils.isEmpty(deviceEntities)){
            for (DeviceEntity deviceEntity : deviceEntities){
                DeviceEntity entity = new DeviceEntity();
                entity.setId(deviceEntity.getId());
                entity.setDeviceGuid(deviceEntity.getDeviceGuid());
                devices.add(entity);
            }
        }

        return devices;
    }

}
